import SearchForm from '@/components/searchform';
import {
  BLOCK_HEADER_HEIGHT,
  commonText,
  MODAL_FOOTER_HEIGHT,
  MODAL_HEADER_HEIGHT,
  MODAL_PADDING_HEIGHT,
} from '@/utils/utils';
import { Grid, Header } from 'gantd';
import type { ReactNode } from 'react';
import React, { forwardRef, useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { columns, searchFormschema, searchUISchema } from './schema';

interface SelectorPanelProps {
  title?: string | ReactNode;
  visible: boolean;
  multiple?: boolean;
  onChange?: (rowKeys: string[], rows: any[]) => void;
  onCancel?: () => void;
  onOk?: (selectedRowKeys: string[], selectedRows: object[]) => void;
  confirmLoading: boolean;
  ref?: any;
  [propName: string]: any;
}

const SelectorView = forwardRef((props: SelectorPanelProps, ref: any) => {
  const {
    userId,
    loading,
    visible,
    value,
    valueProp,
    multiple,
    modalHei,
    tableHei,
    selectedRowKeys,
    selectedRows,
    onChange,
    setSelectedItem,
    dispatch,
    withAuth,
    listRole4selector,
    listRole4selectorParams,
    listRole4selectorTotal,
  } = props;

  const [searchHeight, setSearchHeight] = useState<number>(0);

  const fetch = useCallback(
    (params: object = {}, page: number = 0, pageSize: number = 50) => {
      dispatch({
        type: 'selectors/listRole',
        payload: { withAuth, params: { page, pageSize, ...params } },
      });
    },
    [withAuth],
  );

  const initFetch = useCallback(() => {
    fetch();
    value.length && setSelectedItem(value, []);
  }, [value]);

  const handlerSelect = useCallback((rowKeys, rows) => {
    setSelectedItem(rowKeys, rows);
    onChange && onChange(rowKeys, rows);
  }, []);

  const onSearch = useCallback((params) => {
    fetch(params);
  }, []);

  const onSearchSizeChange = useCallback(({ height }: any) => {
    setSearchHeight(height);
  }, []);

  //分页变化
  const onChangePage = useCallback((page, pageSize) => {
    const { filterInfo } = listRole4selectorParams;
    fetch(filterInfo, page, pageSize);
  }, []);

  const gridHei = useMemo(() => {
    const diff =
      MODAL_HEADER_HEIGHT + MODAL_PADDING_HEIGHT * 2 + MODAL_FOOTER_HEIGHT + searchHeight + BLOCK_HEADER_HEIGHT;
    if (!modalHei) return tableHei;
    const hei = modalHei - diff;
    return (hei > 0 && hei) || 'auto';
  }, [modalHei, tableHei, searchHeight]);

  useEffect(() => {
    if (typeof visible === 'boolean') {
      visible && initFetch();
    } else {
      initFetch();
    }
  }, [visible]);

  return (
    <>
      <SearchForm
        searchKey={`role_selector:${userId}`}
        title={commonText.smartSearchTitleText}
        headerProps={{ type: 'line', bottomLine: false }}
        onSearch={onSearch}
        schema={searchFormschema}
        onSizeChange={onSearchSizeChange}
        uiSchema={searchUISchema}
      />
      <Header title={commonText.smartGridTitleText} type="line" />
      <Grid
        hideMenuItemExport
        columns={columns}
        rowkey={valueProp}
        dataSource={listRole4selector}
        loading={loading}
        height={gridHei}
        rowSelection={{
          type: multiple ? 'multiple' : 'single',
          selectedKeys: selectedRowKeys,
          selectedRows,
          onSelect: handlerSelect,
        }}
        boxColumnIndex={['userLoginName', 'roleName']}
        pagination={{
          // pageSizeOptions: ['2', '50', '100', '150', '200'],
          total: listRole4selectorTotal, //总条数
          beginIndex: listRole4selectorParams.pageInfo.beginIndex, //当前页数
          pageSize: listRole4selectorParams.pageInfo.pageSize, //每页显示数
          onChange: onChangePage,
        }}
      />
    </>
  );
});

SelectorView.defaultProps = {
  multiple: false,
  tableHei: 'auto',
  value: [],
  valueProp: 'id',
  withAuth: false,
};

export interface ConnectProps extends SelectorPanelProps {
  viewRef: object;
}
class ConnectComp extends React.Component<ConnectProps> {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
  };
  static defaultProps = {
    viewRef: {},
  };

  componentDidMount() {
    this.props.viewRef.current = this;
  }
  setSelectedItem = (selectedRowKeys: [string], selectedRows: [any]) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  getValues = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    return { selectedRowKeys, selectedRows };
  };
  render() {
    const { selectedRowKeys, selectedRows } = this.state;
    return (
      <SelectorView
        {...this.props}
        selectedRowKeys={selectedRowKeys}
        selectedRows={selectedRows}
        setSelectedItem={this.setSelectedItem}
      />
    );
  }
}
export default connect(({ selectors, user, loading }: any) => ({
  loading: loading.effects['selectors/listRole'],
  userId: user.currentUser.id,
  listRole4selector: selectors.listRole4selector,
  listRole4selectorParams: selectors.listRole4selectorParams,
  listRole4selectorTotal: selectors.listRole4selectorTotal,
}))(ConnectComp);
